package com.by_man.presenter.module_health_records.access_records;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by man on 2017-03-17.
 */
public class MedicationHistoryActivity extends AppCompatActivity {
    private ListView lv;
    private Button sear;
    private EditText searchView;
    private Spinner mySpinner;

    private ArrayList<String> drugname = new ArrayList<String> ();
    private ArrayList<String> drugtype = new ArrayList<String> ();
    private ArrayList<String> drugrate = new ArrayList<String> ();
    private ArrayList<String> drugdosage = new ArrayList<String> ();
    private ArrayList<String> drugstart = new ArrayList<String> ();
    private ArrayList<String> drugend = new ArrayList<String> ();
    private ArrayList<String> drugstate=new ArrayList<String>();

    private RequestQueue rQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medication_history);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MedicationRecordActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MedicationRecordActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        sear = (Button) findViewById(R.id.medinice_search);
        lv= (ListView) findViewById(R.id.themedinice_his);
        searchView=(EditText)findViewById(R.id.search);

        HashMap<String, String> params = new HashMap<>();
        params.put("token", UserInfos.token);
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
        PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                IpAddress.Medication_History, params,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            JSONObject temp;
                            for (int j = 0; j < jsonArray.length(); j++) {
                                temp = (JSONObject) jsonArray.get(j);
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                final String drug_name = temp.getString("drug_name");
                                final String drug_type = temp.getString("drug_type");
                                final String drug_rate = temp.getString("drug_rate");
                                final String drug_dosage = temp.getString("drug_dosage");
                                final String drug_start = temp.getString("drug_start");
                                final String drug_end = temp.getString("drug_end");
                                //  Log.i("drug_end", String.valueOf(drug_end.length()));
                                String state = temp.getString("state");

                                drugname.add(temp.getString("drug_name"));
                                drugtype.add(temp.getString("drug_type"));
                                drugrate.add(temp.getString("drug_rate"));
                                drugdosage.add(temp.getString("drug_dosage"));
                                drugstart.add(temp.getString("drug_start"));
                                drugend.add(temp.getString("drug_end").length()==0?"此药物长期使用":temp.getString("drug_end"));
                                drugstate.add(temp.getString("state"));

                                if(state.equals("1"))
                                {
                                    state="短期用药";
                                }else {
                                    state = "长期用药";
                                }
                                map.put("name", drug_name);
                                map.put("type", drug_type);
                                map.put("rate", drug_rate);
                                map.put("dosage", drug_dosage);
                                map.put("start", drug_start);
                                map.put("end", drug_end);
                                map.put("state", state);
                                listItem.add(map);
                                int a0 = drugname.size();
                                Log.e("a0a0a0", a0 + "");
                            }

                            SimpleAdapter adapter;
                            adapter = new SimpleAdapter(MedicationHistoryActivity.this, listItem, R.layout.item_listview_medication_history,
                                    new String[]{"name","state", "type", "rate", "dosage", "start", "end"},
                                    new int[]{R.id.list_medinice_name, R.id.list_medinice_state,R.id.list_medinice_type,
                                            R.id.list_medinice_rate, R.id.list_medinice_amount, R.id.list_medinice_star, R.id.list_medinice_end});
                            lv.setAdapter(adapter);
                        } catch (JSONException je) {
                            je.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("MedicationHistoryError",volleyError.getMessage(),volleyError);
                    }
                });
        rQueue.add(stringRequest);
        int a1 = drugname.size();
        Log.e("a1a1a1", a1 + "");

        sear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String drugsearch;
                drugsearch = searchView.getText().toString().trim();
                final ArrayList<HashMap<String, Object>> listItem1 = new ArrayList<HashMap<String, Object>>();
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("token", UserInfos.token);
                params.put("name", drugsearch);
                PostStringRequest stringRequest1 = new PostStringRequest(Request.Method.POST,
                        IpAddress.Search_Medication, params,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {
                                try {
                                    JSONArray jsonArray = new JSONArray(s);
                                    JSONObject temp;
                                    for (int j = 0; j < jsonArray.length(); j++) {
                                        temp = (JSONObject) jsonArray.get(j);
                                        HashMap<String, Object> map = new HashMap<String, Object>();
                                        final String drug_name = temp.getString("drug_name");
                                        final String drug_type = temp.getString("drug_type");
                                        final String drug_rate = temp.getString("drug_rate");
                                        final String drug_dosage = temp.getString("drug_dosage");
                                        final String drug_start = temp.getString("drug_start");
                                        final String drug_end = temp.getString("drug_end");

                                        drugname.set(j, temp.getString("drug_name"));
                                        drugtype.set(j, temp.getString("drug_type"));
                                        drugrate.set(j, temp.getString("drug_rate"));
                                        drugdosage.set(j, temp.getString("drug_dosage"));
                                        drugstart.set(j, temp.getString("drug_start"));
                                        drugend.set(j, temp.getString("drug_end"));

                                        map.put("name", drug_name);
                                        map.put("type", drug_type);
                                        map.put("rate", drug_rate);
                                        map.put("dosage", drug_dosage);
                                        map.put("start", drug_start);
                                        map.put("end", drug_end);

                                        listItem1.add(map);
                                    }

                                    SimpleAdapter adapter;
                                    adapter = new SimpleAdapter(MedicationHistoryActivity.this, listItem1, R.layout.item_listview_medication_history,
                                            new String[]{"name", "type", "rate", "dosage", "start", "end"},
                                            new int[]{R.id.list_medinice_name, R.id.list_medinice_type, R.id.list_medinice_rate,
                                                    R.id.list_medinice_amount, R.id.list_medinice_star, R.id.list_medinice_end});
                                    lv.setAdapter(adapter);

                                } catch (JSONException je) {
                                    je.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.e("MedicationHistoryError",volleyError.getMessage(),volleyError);
                            }
                        });
                rQueue.add(stringRequest1);
            }
        });

        mySpinner = (Spinner) findViewById(R.id.medinice_spinner);
        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                                @Override
                                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                                    if (position == 0) {
                                                        return;
                                                    }
                                                    //按时间排序
                                                    if (position == 1) {
                                                        String cardNumber = MedicationHistoryActivity.this.getResources().getStringArray(R.array.paixu)[position];
                                                        TextView paixuView = (TextView) findViewById(R.id.paixu);
                                                        mySpinner.getSelectedItem().toString();
                                                        paixuView.setText(cardNumber);
                                                        final ArrayList<HashMap<String, Object>> listItem2 = new ArrayList<HashMap<String, Object>>();
                                                        HashMap<String,String> params = new HashMap<String, String>();
                                                        params.put("token", UserInfos.token);
                                                        PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                                                                IpAddress.Sort_Medication_By_Time, params,
                                                                new Response.Listener<String>() {
                                                                    @Override
                                                                    public void onResponse(String s) {
                                                                        try {
                                                                            JSONArray jsonArray = new JSONArray(s);
                                                                            JSONObject temp;
                                                                            for (int j = 0; j < jsonArray.length(); j++) {
                                                                                temp = (JSONObject) jsonArray.get(j);
                                                                                HashMap<String, Object> map = new HashMap<String, Object>();
                                                                                final String drug_name = temp.getString("drug_name");
                                                                                final String drug_type = temp.getString("drug_type");
                                                                                final String drug_rate = temp.getString("drug_rate");
                                                                                final String drug_dosage = temp.getString("drug_dosage");
                                                                                final String drug_start = temp.getString("drug_start");
                                                                                final String drug_end = temp.getString("drug_end");
                                                                                String state = temp.getString("state");
                                                                                if (state.equals("1")) {
                                                                                    state = "短期用药";
                                                                                } else {
                                                                                    state = "长期用药";
                                                                                }
                                                                                map.put("name", drug_name);
                                                                                map.put("type", drug_type);
                                                                                map.put("rate", drug_rate);
                                                                                map.put("dosage", drug_dosage);
                                                                                map.put("start", drug_start);
                                                                                map.put("end", drug_end);
                                                                                map.put("state", state);
                                                                                listItem2.add(map);
                                                                            }

                                                                            SimpleAdapter adapter;
                                                                            adapter = new SimpleAdapter(MedicationHistoryActivity.this, listItem2, R.layout.item_listview_medication_history,
                                                                                    new String[]{"name", "type", "rate", "dosage", "start", "end"},
                                                                                    new int[]{R.id.list_medinice_name, R.id.list_medinice_type, R.id.list_medinice_rate,
                                                                                            R.id.list_medinice_amount, R.id.list_medinice_star, R.id.list_medinice_end});
                                                                            lv.setAdapter(adapter);
                                                                        } catch (JSONException je) {
                                                                            je.printStackTrace();
                                                                        }
                                                                    }
                                                                },
                                                                new Response.ErrorListener() {
                                                                    @Override
                                                                    public void onErrorResponse(VolleyError volleyError) {
                                                                        Log.e("MedicationHistoryError",volleyError.getMessage(),volleyError);
                                                                    }
                                                                });
                                                        rQueue.add(stringRequest);
                                                    }

                                                    //按药名排序
                                                    if (position == 2) {
                                                        String cardNumber = MedicationHistoryActivity.this.getResources().getStringArray(R.array.paixu)[position];
                                                        Log.i("123", cardNumber);
                                                        TextView paixuView = (TextView) findViewById(R.id.paixu);
                                                        mySpinner.getSelectedItem().toString();
                                                        paixuView.setText(cardNumber);
                                                        final ArrayList<HashMap<String, Object>> listItem3 = new ArrayList<HashMap<String, Object>>();
                                                        HashMap<String,String> params = new HashMap<String, String>();
                                                        params.put("token", UserInfos.token);
                                                        PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                                                                IpAddress.Sort_Medication_By_Name, params,
                                                                new Response.Listener<String>() {
                                                                    @Override
                                                                    public void onResponse(String s) {
                                                                        try {
                                                                            JSONArray jsonArray = new JSONArray(s);
                                                                            JSONObject temp;
                                                                            for (int j = 0; j < jsonArray.length(); j++) {
                                                                                temp = (JSONObject) jsonArray.get(j);
                                                                                HashMap<String, Object> map = new HashMap<String, Object>();
                                                                                final String drug_name = temp.getString("drug_name");
                                                                                final String drug_type = temp.getString("drug_type");
                                                                                final String drug_rate = temp.getString("drug_rate");
                                                                                final String drug_dosage = temp.getString("drug_dosage");
                                                                                final String drug_start = temp.getString("drug_start");
                                                                                final String drug_end = temp.getString("drug_end");
                                                                                String state = temp.getString("state");
                                                                                if (state.equals("1")) {
                                                                                    state = "短期用药";
                                                                                } else {
                                                                                    state = "长期用药";
                                                                                }
                                                                                map.put("name", drug_name);
                                                                                map.put("type", drug_type);
                                                                                map.put("rate", drug_rate);
                                                                                map.put("dosage", drug_dosage);
                                                                                map.put("start", drug_start);
                                                                                map.put("end", drug_end);
                                                                                map.put("state", state);
                                                                                listItem3.add(map);
                                                                            }

                                                                            SimpleAdapter adapter;
                                                                            adapter = new SimpleAdapter(MedicationHistoryActivity.this, listItem3, R.layout.item_listview_medication_history,
                                                                                    new String[]{"name", "type", "rate", "dosage", "start", "end"},
                                                                                    new int[]{R.id.list_medinice_name, R.id.list_medinice_type, R.id.list_medinice_rate,
                                                                                            R.id.list_medinice_amount, R.id.list_medinice_star, R.id.list_medinice_end});
                                                                            lv.setAdapter(adapter);
                                                                        } catch (JSONException je) {
                                                                            je.printStackTrace();
                                                                        }
                                                                    }
                                                                },
                                                                new Response.ErrorListener() {
                                                                    @Override
                                                                    public void onErrorResponse(VolleyError volleyError) {
                                                                        Log.e("MedicationHistoryError",volleyError.getMessage(),volleyError);
                                                                    }
                                                                });
                                                        rQueue.add(stringRequest);
                                                    }
                                                }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
                                            });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("position", position + "");
                int a = drugdosage.size();
                Log.e("aaaaaa", a + "");

                new AlertDialog.Builder(MedicationHistoryActivity.this).setTitle(drugname.get(position))//设置对话框标题
                        .setMessage("药品规格:" + drugtype.get(position) + "mg/片"+"\n"
                                + "用药频次:" + drugrate.get(position) +"次/天"+"\n" +
                                "用药剂量:" + drugdosage.get(position) +  "片(粒)/次"+"\n" +
                                "开始时间:" + drugstart.get(position) + "\n" +
                                "结束时间:" + drugend.get(position))//设置显示的内容
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                return;
                            }
                        }).show();//在按键响应事件中显示此对话框
            }

        });
    }
}
